package com.cn.esermis.dpld.business;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.cn.esermis.coding.PollutionGas;
import com.cn.esermis.constant.Constant;
import com.cn.esermis.datawarn.common.ExceptionDataDispose;
import com.cn.esermis.dpld.entity.*;
import com.cn.esermis.dpld.mapper.AirMonitorHourRecordMapper;
import com.cn.esermis.dpld.model.OutletAndFactorVo;
import com.cn.esermis.dpld.service.*;
import com.cn.esermis.model.CP;
import com.cn.esermis.model.FactorModel;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Component
@Log4j2
public class MonitorBusiness {

    @Resource
    private IWaterMonitorMinuteRecordService waterMonitorMinuteRecordService;
    @Resource
    private IWaterMonitorHourRecordService waterMonitorHourRecordService;
    @Resource
    private IAirMonitorMinuteRecordService airMonitorMinuteRecordService;
    @Autowired(required = true)
    private ExceptionDataDispose exceptionDataDispose;
    @Resource
    private IDataAcquisitionInstrumentService dataAcquisitionInstrumentService;
    @Resource
    private IExcepLogService excepLogService;
    @Resource
    private IAirMonitorHourRecordService airMonitorHourRecordService;
    @Resource
    private AirMonitorHourRecordMapper airMonitorHourRecordMapper;
    @Resource
    private IPostMarkingService postMarkingService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private IPreMarkingService preMarkingService;

    @PostConstruct
    public void loadData() {

        List<OutletAndFactorVo> selectlist = dataAcquisitionInstrumentService.selectlist();
        redisTemplate.opsForValue().set("dataAcquisitionInstruments", JSON.toJSONString(selectlist));
        List<PreMarking> preMarking = preMarkingService.getNewMarking();
        if (preMarking != null){
            preMarking.forEach(x->{
                if (x.getMnCode()!=null)
                redisTemplate.opsForValue().set(x.getMnCode(), JSON.toJSONString(x));
            });
        }
        // 处理读取到的数据
    }



    /**
     * 处理消息入库
     *
     * @param msg
     */
//    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void inboundOperations(JSONObject msg) {
        // 消息入库
        if (msg == null) {
            return;
        }
        FactorModel factorModel = new FactorModel().factorModel(msg);
        List<CP> cp = factorModel.getCP();
//        log.info("入库数据：{}", msg);
        try {
            if (!cp.isEmpty() && factorModel.getST().equals(Constant.ST_AIR)) {
                // 气体检测
                if (factorModel.getCN().equals(Constant.MINUTE)) {
                    // 分钟数据入库
                    List<AirMonitorMinuteRecord> listData = new ArrayList<>();
                    cp.forEach(x -> {
                        AirMonitorMinuteRecord airMonitorMinuteRecord = new AirMonitorMinuteRecord();
                        airMonitorMinuteRecord.setQn(factorModel.getQN());
                        airMonitorMinuteRecord.setSt(factorModel.getST());
                        airMonitorMinuteRecord.setCn(factorModel.getCN());
                        airMonitorMinuteRecord.setPw(factorModel.getPW());
                        airMonitorMinuteRecord.setMn(factorModel.getMN());
                        airMonitorMinuteRecord.setFlag(factorModel.getFlag());
                        airMonitorMinuteRecord.setDataTime(factorModel.getDataTime());
                        airMonitorMinuteRecord.setFactor(x.getFactor());
                        airMonitorMinuteRecord.setMin(x.getMin());
                        airMonitorMinuteRecord.setMax(x.getMax());
                        airMonitorMinuteRecord.setAvg(x.getAvg());
                        airMonitorMinuteRecord.setCou(x.getCou());
                        airMonitorMinuteRecord.setFactorFlag(x.getFlag());
                        airMonitorMinuteRecord.setZsAvg(x.getZsAvg());
                        airMonitorMinuteRecord.setZsMax(x.getZsMax());
                        airMonitorMinuteRecord.setZsMin(x.getZsMin());
                        airMonitorMinuteRecord.setRtd(x.getRtd());
                        airMonitorMinuteRecord.setCreatTime(new Date());
                        try {
                            airMonitorMinuteRecord.setWorkCondition(sendMessage(factorModel.getDataTime(),factorModel.getMN()));
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }
                        try {
                            // 计算时间
                            Optional<OutletAndFactorVo> first = getloadData().stream().filter(d ->d.getMnCode()!=null && d.getMnCode().equals(factorModel.getMN()) &&  d.getFactor()!=null && d.getFactor().equals(x.getFactor())).findFirst();
                            if (first.isPresent()){
                                int flag = 0;
                                if(x.getZsAvg()!=null){
                                    flag = 1;
                                    airMonitorMinuteRecord.setIsExceed(exceptionDataDispose.ExceedData(factorModel.getMN(), x.getFactor(), x.getZsAvg().doubleValue()));
                                }else{
                                    flag = 2;
                                    airMonitorMinuteRecord.setIsExceed(exceptionDataDispose.ExceedData(factorModel.getMN(), x.getFactor(), x.getAvg()!=null?x.getAvg().doubleValue():0));
                                }
                                if ((airMonitorMinuteRecord.getIsExceed()!=null && airMonitorMinuteRecord.getIsExceed().equals("1"))){
                                    saveExcepLog(x, airMonitorMinuteRecord, flag);
                                }
                            }

                        } catch (Exception e) {
                            log.error("调用 ExceptionDataDispose1 方法异常{} 当前参数为:{}",e,airMonitorMinuteRecord);
                            e.printStackTrace();
                        }
                        listData.add(airMonitorMinuteRecord);

                    });
                    if (airMonitorMinuteRecordService.saveBatch(listData)){
                        log.info("入库成功:{}",msg);
                    }
                }
                else if (factorModel.getCN().equals(Constant.HOUR)) {
                    // 小时数据入库
                    List<AirMonitorHourRecord> listData = new ArrayList<>();
                    cp.forEach(x -> {
                        AirMonitorHourRecord airMonitorHourRecord = new AirMonitorHourRecord();
                        airMonitorHourRecord.setQn(factorModel.getQN());
                        airMonitorHourRecord.setSt(factorModel.getST());
                        airMonitorHourRecord.setCn(factorModel.getCN());
                        airMonitorHourRecord.setPw(factorModel.getPW());
                        airMonitorHourRecord.setMn(factorModel.getMN());
                        airMonitorHourRecord.setFlag(factorModel.getFlag());
                        airMonitorHourRecord.setDataTime(factorModel.getDataTime());
                        airMonitorHourRecord.setFactor(x.getFactor());
                        airMonitorHourRecord.setMin(x.getMin());
                        airMonitorHourRecord.setMax(x.getMax());
                        airMonitorHourRecord.setAvg(x.getAvg());
                        airMonitorHourRecord.setCou(x.getCou());
                        airMonitorHourRecord.setFactorFlag(x.getFlag());
                        airMonitorHourRecord.setZsAvg(x.getZsAvg());
                        airMonitorHourRecord.setZsMax(x.getZsMax());
                        airMonitorHourRecord.setZsMin(x.getZsMin());
                        airMonitorHourRecord.setRtd(x.getRtd());
                        airMonitorHourRecord.setCreatTime(new Date());
                        try {
                            airMonitorHourRecord.setWorkCondition(sendHoursMessage(factorModel.getDataTime(),factorModel.getMN()));
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                        try {
                            Optional<OutletAndFactorVo> first = getloadData().stream().filter(d ->
                                    d.getMnCode()!=null && d.getMnCode().equals(factorModel.getMN())
                                            &&  d.getFactor()!=null && d.getFactor().equals(x.getFactor())).findFirst();
                            if (first.isPresent()) {
                                int flag = 0, flag1 = 0;
                                if(x.getZsMin()!=null){
                                    flag = 1;
                                    airMonitorHourRecord.setIsLose(exceptionDataDispose.LoseData(x.getZsAvg().doubleValue()));
                                }else{
                                    flag = 2;
                                    airMonitorHourRecord.setIsLose(exceptionDataDispose.LoseData(x.getZsAvg()!=null?x.getZsAvg().doubleValue():0));
                                }
                                if(x.getZsAvg()!=null){
                                    flag1 = 1;
                                    airMonitorHourRecord.setIsExceed(exceptionDataDispose.ExceedData(factorModel.getMN(), x.getFactor(), x.getZsAvg().doubleValue()));
//                                    airMonitorHourRecord.setIsSix(exceptionDataDispose.SixData("1",factorModel.getMN(), x.getFactor(),x.getZsAvg().doubleValue(), factorModel.getDataTime()));
                                }else{
                                    flag1 = 2;
                                    airMonitorHourRecord.setIsExceed(exceptionDataDispose.ExceedData(factorModel.getMN(), x.getFactor(), x.getAvg()!=null?x.getAvg().doubleValue():0));
//                                    airMonitorHourRecord.setIsSix(exceptionDataDispose.SixData("0",factorModel.getMN(), x.getFactor(),x.getAvg()!=null?x.getAvg().doubleValue():0, factorModel.getDataTime()));
                                }
                                if ((airMonitorHourRecord.getIsExceed()!=null && airMonitorHourRecord.getIsExceed().equals("1") )||
                                        (airMonitorHourRecord.getIsLose()!=null && airMonitorHourRecord.getIsLose().equals("1") )||
                                        (airMonitorHourRecord.getIsSix()!=null && airMonitorHourRecord.getIsSix().equals("1"))){
                                    saveExcepLog(x, airMonitorHourRecord,flag,flag1);
                                }
                            }
                        } catch (Exception e) {
                            log.error("调用 ExceptionDataDispose3 方法异常{} 当前参数为:{}",e,airMonitorHourRecord);
                            e.printStackTrace();
                        }
                        listData.add(airMonitorHourRecord);
                    });
                    if(airMonitorHourRecordService.saveBatch(listData)){
                        log.info("入库成功:{}",msg);
                    }
                }
            } else if (factorModel.getST().equals(Constant.ST_WATER)) {
                // 污水检测
                if (factorModel.getCN().equals(Constant.MINUTE)) {
                    // 分钟数据入库
                    List<WaterMonitorMinuteRecord> listData = new ArrayList<>();
                    cp.forEach(x -> {
                        WaterMonitorMinuteRecord waterMonitorMinuteRecord = new WaterMonitorMinuteRecord();
                        waterMonitorMinuteRecord.setQn(factorModel.getQN());
                        waterMonitorMinuteRecord.setSt(factorModel.getST());
                        waterMonitorMinuteRecord.setCn(factorModel.getCN());
                        waterMonitorMinuteRecord.setPw(factorModel.getPW());
                        waterMonitorMinuteRecord.setMn(factorModel.getMN());
                        waterMonitorMinuteRecord.setFlag(factorModel.getFlag());
                        waterMonitorMinuteRecord.setDataTime(factorModel.getDataTime());
                        waterMonitorMinuteRecord.setFactor(x.getFactor());
                        waterMonitorMinuteRecord.setMin(x.getMin());
                        waterMonitorMinuteRecord.setMax(x.getMax());
                        waterMonitorMinuteRecord.setAvg(x.getAvg());
                        waterMonitorMinuteRecord.setCou(x.getCou());
                        waterMonitorMinuteRecord.setFactorFlag(x.getFlag());
                        waterMonitorMinuteRecord.setRtd(x.getRtd());
                        waterMonitorMinuteRecord.setCreatTime(new Date());
                        try {
                            waterMonitorMinuteRecord.setWorkCondition(sendMessage(factorModel.getDataTime(),factorModel.getMN()));
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }
                        try {
                            Optional<OutletAndFactorVo> first = getloadData().stream().filter(d ->
                                    d.getMnCode()!=null && d.getMnCode().equals(factorModel.getMN()) &&
                                            d.getFactor()!=null &&  d.getFactor().equals(x.getFactor())).findFirst();
                            if (first.isPresent()){
                                waterMonitorMinuteRecord.setIsExceed(exceptionDataDispose.ExceedData(factorModel.getMN(), x.getFactor(), x.getAvg()!=null?x.getAvg().doubleValue():0));
                                if ((waterMonitorMinuteRecord.getIsExceed()!=null && waterMonitorMinuteRecord.getIsExceed().equals("1"))){
                                    saveExcepLog(x, waterMonitorMinuteRecord);
                                }
                            }
                        } catch (Exception e) {
                            log.error("调用 ExceptionDataDispose4 方法异常{} 当前参数为:{}",e,waterMonitorMinuteRecord);
                            e.printStackTrace();
                        }
                        listData.add(waterMonitorMinuteRecord);
                    });
                    if(waterMonitorMinuteRecordService.saveBatch(listData)){
                        log.info("入库成功:{}",msg);
                    }
                }
                else if
                (factorModel.getCN().equals(Constant.HOUR)) {
                    // 小时数据入库
                    List<WaterMonitorHourRecord> listData = new ArrayList<>();
                    cp.forEach(x -> {
                        WaterMonitorHourRecord waterMonitorHourRecord = new WaterMonitorHourRecord();
                        waterMonitorHourRecord.setQn(factorModel.getQN());
                        waterMonitorHourRecord.setSt(factorModel.getST());
                        waterMonitorHourRecord.setCn(factorModel.getCN());
                        waterMonitorHourRecord.setPw(factorModel.getPW());
                        waterMonitorHourRecord.setMn(factorModel.getMN());
                        waterMonitorHourRecord.setFlag(factorModel.getFlag());
                        waterMonitorHourRecord.setDataTime(factorModel.getDataTime());
                        waterMonitorHourRecord.setFactor(x.getFactor());
                        waterMonitorHourRecord.setMin(x.getMin());
                        waterMonitorHourRecord.setMax(x.getMax());
                        waterMonitorHourRecord.setAvg(x.getAvg());
                        waterMonitorHourRecord.setCou(x.getCou());
                        waterMonitorHourRecord.setFactorFlag(x.getFlag());
                        waterMonitorHourRecord.setRtd(x.getRtd());
                        waterMonitorHourRecord.setCreatTime(new Date());
                        try {
                            waterMonitorHourRecord.setWorkCondition(sendHoursMessage(factorModel.getDataTime(),factorModel.getMN()));
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                        try {
                            Optional<OutletAndFactorVo> first = getloadData().stream().filter(d -> d.getMnCode()!=null
                                    && d.getMnCode().equals(factorModel.getMN())
                                    && d.getFactor()!=null && d.getFactor().equals(x.getFactor())).findFirst();
                            if (first.isPresent()) {
                                waterMonitorHourRecord.setIsLose(exceptionDataDispose.LoseData(x.getAvg()!=null?x.getAvg().doubleValue():0));
                                waterMonitorHourRecord.setIsExceed(exceptionDataDispose.ExceedData(factorModel.getMN(), x.getFactor(), x.getAvg()!=null?x.getAvg().doubleValue():0));
//                                waterMonitorHourRecord.setIsSix(exceptionDataDispose.SixData("0",factorModel.getMN(), x.getFactor(),x.getAvg()!=null?x.getAvg().doubleValue():0, factorModel.getDataTime()));
                                if ((waterMonitorHourRecord.getIsExceed()!=null && waterMonitorHourRecord.getIsExceed().equals("1") )||
                                        (waterMonitorHourRecord.getIsLose()!=null && waterMonitorHourRecord.getIsLose().equals("1") )||
                                        (waterMonitorHourRecord.getIsSix()!=null && waterMonitorHourRecord.getIsSix().equals("1"))){
                                    saveExcepLog(x, waterMonitorHourRecord);
                                }
                            }
                        } catch (Exception e) {
                            log.error("调用 ExceptionDataDispose6 方法异常{} 当前参数为:{}",e,waterMonitorHourRecord);
                            e.printStackTrace();
                        }
                        listData.add(waterMonitorHourRecord);
                    });
                    if (waterMonitorHourRecordService.saveBatch(listData)){
                        log.info("入库成功:{}",msg);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
//            log.error("插入数据库异常："+e);
        }
    }

    private void saveExcepLog(CP x, AirMonitorMinuteRecord record, int flag) {
        ExcepLog excepLog = new ExcepLog();
        Optional<OutletAndFactorVo> first = getloadData().stream().filter(d ->d.getMnCode()!=null && d.getMnCode().equals(record.getMn()) &&  d.getFactor()!=null && d.getFactor().equals(x.getFactor())).findFirst();
        if (first.isPresent() && record.getWorkCondition().equals(1) && (record.getFactorFlag()==null || record.getFactorFlag().equals("N"))) {
            excepLog.setOutletName(first.get().getOutletName());
            excepLog.setOutletCode(first.get().getOutletCode());
            excepLog.setMn(record.getMn());
            excepLog.setFactor(record.getFactor());
            excepLog.setExcepTime(shijian(record.getDataTime()));
            if (record.getIsExceed()!=null && record.getIsExceed().equals("1")){
                // 瞬时值超限
                if (flag==1){
                    excepLog.setInstantOut(String.valueOf(x.getZsAvg()));
                }else {
                    excepLog.setInstantOut(String.valueOf(x.getAvg()));
                }
            }
            excepLogService.save(excepLog);
        }
    }

    private void saveExcepLog(CP x, AirMonitorHourRecord record, int flag, int flag1) {
        ExcepLog excepLog = new ExcepLog();
        Optional<OutletAndFactorVo> first = getloadData().stream().filter(d ->
                d.getMnCode()!=null && d.getMnCode().equals(record.getMn())
                &&  d.getFactor()!=null && d.getFactor().equals(x.getFactor())).findFirst();
        if (first.isPresent()&& record.getWorkCondition().equals(1)&& (record.getFactorFlag()==null || record.getFactorFlag().equals("N"))) {
            excepLog.setOutletName(first.get().getOutletName());
            excepLog.setOutletCode(first.get().getOutletCode());
            excepLog.setMn(record.getMn());
            excepLog.setFactor(record.getFactor());
            excepLog.setExcepTime(shijian(record.getDataTime()));
            // 负值异常
            if (record.getIsLose()!=null && record.getIsLose().equals("1")){
                if (flag==1){
                    excepLog.setLoseData(String.valueOf(x.getZsAvg()));
                }else {
                    excepLog.setLoseData(String.valueOf(x.getAvg()));
                }
                String id = addExcepLog(record.getFactor(), "1", record.getMn(),x,excepLog,record.getDataTime());
                excepLog.setDisposalLose(id);
            }
            // 六小时均值异常
            if (record.getIsSix()!=null && record.getIsSix().equals("1")){
                if (flag1==1){
                    excepLog.setSixLast(String.valueOf(x.getZsAvg()));
                }else {
                    excepLog.setSixLast(String.valueOf(x.getAvg()));
                }
                String id = addExcepLog(record.getFactor(), "2", record.getMn(),x,excepLog,record.getDataTime());
                excepLog.setDisposalSix(id);
            }
            if (record.getIsExceed()!=null && record.getIsExceed().equals("1")){
                // 小时均值超限
                if (flag1==1){
                    excepLog.setAvgOut(String.valueOf(x.getZsAvg()));
                }else {
                    excepLog.setAvgOut(String.valueOf(x.getAvg()));
                }
                String id = addExcepLog(record.getFactor(), "3",record.getMn(),x,excepLog,record.getDataTime());
                excepLog.setDisposal_avg(id);
            }
            excepLogService.save(excepLog);
        }

    }

    private void saveExcepLog(CP x, WaterMonitorMinuteRecord record) {
        ExcepLog excepLog = new ExcepLog();
        Optional<OutletAndFactorVo> first = getloadData().stream().filter(d ->
                d.getMnCode()!=null && d.getMnCode().equals(record.getMn()) &&
                d.getFactor()!=null &&  d.getFactor().equals(x.getFactor())).findFirst();
        if (first.isPresent()&& record.getWorkCondition().equals(1)&& (record.getFactorFlag()==null || record.getFactorFlag().equals("N"))) {
            excepLog.setOutletName(first.get().getOutletName());
            excepLog.setOutletCode(first.get().getOutletCode());
            excepLog.setMn(record.getMn());
            excepLog.setFactor(record.getFactor());
            excepLog.setExcepTime(shijian(record.getDataTime()));
            excepLog.setSixLast(record.getIsSix());
            excepLog.setLoseData(record.getIsLose());
            excepLog.setAvgOut(record.getIsExceed());
            if (record.getIsExceed()!=null && record.getIsExceed().equals("1")){
                // 瞬时值超限
                excepLog.setInstantOut(String.valueOf(x.getAvg()));
            }
            excepLogService.save(excepLog);
        }
    }
    private void saveExcepLog(CP x, WaterMonitorHourRecord record) {
        ExcepLog excepLog = new ExcepLog();
        Optional<OutletAndFactorVo> first = getloadData().stream().filter(d -> d.getMnCode()!=null
                && d.getMnCode().equals(record.getMn())
                && d.getFactor()!=null && d.getFactor().equals(x.getFactor())).findFirst();
        if (first.isPresent() && record.getWorkCondition().equals(1) && (record.getFactorFlag()==null || record.getFactorFlag().equals("N"))) {
            excepLog.setOutletName(first.get().getOutletName());
            excepLog.setOutletCode(first.get().getOutletCode());
            excepLog.setMn(record.getMn());
            excepLog.setFactor(record.getFactor());
            excepLog.setExcepTime(shijian(record.getDataTime()));
            excepLog.setSixLast(record.getIsSix());
            excepLog.setLoseData(record.getIsLose());
            excepLog.setAvgOut(record.getIsExceed());

            if (record.getIsLose() != null && record.getIsLose().equals("1")) {
                String id = addExcepLog(record.getFactor(), "1", record.getMn(),x,excepLog,record.getDataTime());
                excepLog.setLoseData(String.valueOf(x.getAvg()));
                excepLog.setDisposalLose(id);
            }
            if (record.getIsSix() != null && record.getIsSix().equals("1")) {
                String id = addExcepLog(record.getFactor(), "2", record.getMn(),x,excepLog,record.getDataTime());
                excepLog.setSixLast(String.valueOf(x.getAvg()));
                excepLog.setDisposalSix(id);
            }
            if (record.getIsExceed() != null && record.getIsExceed().equals("1")) {
                // 小时均值超限
                String id = addExcepLog(record.getFactor(), "3", record.getMn(),x,excepLog,record.getDataTime());
                excepLog.setAvgOut(String.valueOf(x.getAvg()));
                excepLog.setDisposal_avg(id);
            }
            excepLogService.save(excepLog);
        }

    }

    public boolean isNumeric(String str) {
        return str.matches("\\d+(\\.\\d+)?"); // 正则表达式 \d 是数字字符，+ 表示一次或多次。
    }

    public Integer sendMessage(String time,String mn) throws ParseException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        Object o = redisTemplate.opsForValue().get(mn);
        if (o != null){
            PreMarking preMarking = JSON.parseObject(o.toString(), PreMarking.class);
//            Date date = formatter.parse(time);
            LocalDateTime parse = LocalDateTime.parse(time, formatter);
            LocalDateTime localDateTime = convertDateToLocalDateTime(preMarking.getStartTime());
            if (parse.isAfter(localDateTime)){
                return preMarking.getWorkingCondition();
            }
        }
        return 1;
    }

    public LocalDateTime convertDateToLocalDateTime(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    public Integer sendHoursMessage(String time,String mn) throws ParseException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        Object o = redisTemplate.opsForValue().get(mn);
        if (o != null){
            PreMarking preMarking = JSON.parseObject(o.toString(), PreMarking.class);
//            Date date = formatter.parse(time);
            LocalDateTime parse = LocalDateTime.parse(time, formatter);
            LocalDateTime localDateTime = convertDateToLocalDateTime(preMarking.getStartTime());
            if (parse.isAfter(localDateTime)){
                return preMarking.getWorkingCondition();
            }
        }
        return 1;
    }
    /**
     * 获取工厂排口信息
     */
    private List<OutletAndFactorVo> getloadData() {
        List<OutletAndFactorVo>  dataAcquisitionInstruments = new ArrayList<>();
        Object o = redisTemplate.opsForValue().get("dataAcquisitionInstruments");
        if (o != null){
            dataAcquisitionInstruments = JSON.parseArray(o.toString(), OutletAndFactorVo.class);
        }else {
            dataAcquisitionInstruments = dataAcquisitionInstrumentService.selectlist();
            redisTemplate.opsForValue().set("dataAcquisitionInstruments", JSON.toJSONString(dataAcquisitionInstruments));
        }
        return dataAcquisitionInstruments;
    }
    /**
     * 添加事后处置单信息
     */
    public String addExcepLog(String factor,String dataType,String mn,CP x,ExcepLog excepLog,String qn) {
        PostMarking postMarking = new PostMarking();
        Optional<OutletAndFactorVo> first = getloadData().stream().filter(d -> d.getMnCode()!=null && d.getMnCode().equals(mn) && d.getFactor()!=null && d.getFactor().equals(factor)).findFirst();
        if (first.isPresent()) {
            postMarking.setOutletName(first.get().getOutletName());
            postMarking.setOutletNumber(first.get().getOutletCode());
            postMarking.setManagementNumber(String.valueOf(UuidUtil.getTimeBasedUuid()));
            postMarking.setMnCode(first.get().getMnCode());
            postMarking.setCompanyCode(first.get().getCompanyCode());
            postMarking.setDepartmentCode(first.get().getDepartmentCode());
            postMarking.setFactor(x.getFactor());
            postMarking.setSubmissiontime(qn);
            postMarking.setCreatTime(shijian(qn));
            PollutionGas pollutionGas = PollutionGas.valueOf(factor);
            switch (dataType){
                case "1":
                    //判断是否为负值数据
                    postMarking.setManagementContent("数据异常:监测因子【"+pollutionGas.mean()+"("+pollutionGas.code()+")】采集数据为负数。");
                    postMarking.setNumb(excepLog.getLoseData());
                    break;
                case "2":
                    // //判断是否为六小时恒值数据
                    postMarking.setManagementContent("数据异常：监测因子【"+pollutionGas.mean()+"("+pollutionGas.code()+")】6小时恒值异常。");
                    postMarking.setNumb(excepLog.getSixLast());
                    break;
                case "3":
                    //瞬时值是否为超标数据
                    postMarking.setManagementContent("数据异常：监测因子【"+pollutionGas.mean()+"("+pollutionGas.code()+")】小时均值超限。");
                    postMarking.setNumb(excepLog.getAvgOut());
                    break;
            }
            postMarkingService.save(postMarking);

        }
        return postMarking.getId();
    }
    private static String shijian(String inputDate){
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date date = inputFormat.parse(inputDate);
            return  outputFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return inputDate;
    }

    public static void main(String[] args) {
        System.out.println(shijian("20250121120000"));
    }

}
